import { Directive, ElementRef, Input, OnDestroy, OnInit, Optional, Renderer2, ViewContainerRef } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { InputBoolean, LvSizeLD } from '../core/api';
import { HelpTooltipService } from '../core/services/help-tooltip.service';
import { HelpTooltipComponent } from '../help-tooltip/help-tooltip.component';

@Directive({
  selector: '[lv-input]',
  exportAs: 'lvInput',
  host: {
    class: 'lv-input',
    '[class.lv-input-size-large]': "lvSize === 'large'",
    '[class.lv-input-size-default]': "lvSize === 'default'",
    '(paste)': 'onPaste()',
    '[class.lv-input-disabled]': 'lvDisabled',
    '(ngModelChange)': 'ngModelChange($event)',
  },
})
export class InputDirective implements OnInit, OnDestroy {
  @Input() lvSize: LvSizeLD = 'default';

  @Input() lvPasteAllowed: boolean = true;

  @Input() @InputBoolean() lvDisabled = false; // 是否禁用

  @Input() lvMaxLength: number | { length: number; limitInput?: boolean };

  public valueChange$ = new Subject<string>();

  private status$: Subscription;

  constructor(
    public elementRef: ElementRef<HTMLElement>,
    private viewContainerRef: ViewContainerRef,
    @Optional() private helpTooltipService: HelpTooltipService,
    private render: Renderer2,
  ) {}

  ngOnDestroy(): void {
    this.status$?.unsubscribe();
  }

  ngModelChange(e): void {
    this.valueChange$.next(e);
  }

  onPaste(): boolean {
    if (!this.lvPasteAllowed) {
      return false;
    }
    return undefined;
  }

  ngOnInit(): void {
    const componentRef = this.viewContainerRef.createComponent(HelpTooltipComponent);
    this.render.addClass(componentRef.location.nativeElement, 'lv-input-help-tooltip');
    this.status$ = this.helpTooltipService?.status.subscribe(({ lvContent, lvIcon }): void => {
      if (this.elementRef.nativeElement.classList.contains('lv-spinner-input')) {
        this.render.setStyle(this.elementRef.nativeElement, 'padding-right', lvContent && lvIcon ? '16px' : '8px');
      } else {
        this.render.setStyle(this.elementRef.nativeElement, 'padding-right', lvContent && lvIcon ? '28px' : '8px');
      }
    });
  }
}
